#!/bin/bash


function showBar {
	percDone=$(echo 'scale=2;'$1/$2*100 | bc)
	let "perc=$1*100/$2"
	let "barTmp=$(tput cols)-10"
	barLen=$(echo 'scale=2;'$1/$2*$barTmp | bc)
	barLen=${barLen/\.*}
	bar=''
	fills=''
	if [[ $barLen != [0-9]* ]]; then
		barLen=0
	fi

	for (( b=0; b<$barLen; b++ ))
	do
		bar=$bar"="
	done
	blankSpaces=$(echo $(($barTmp-$barLen)))
	
	for (( f=0; f<$blankSpaces; f++ ))
	do
		fills=$fills"_"
	done
	clear
	echo -e $prompt
	echo '['$bar'>'$fills'] - '$perc'%'
}

if [ $# -ne 2 ] || [ $1 = '-h' ]
then
	echo -e "\tFirst arg : DES password file\n\tsecond arg : dictionary"
fi
bool=true
[ -e $1 ] || ( bool=false ; echo -e "Le fichier $1 est invalide" )
[ -e $2 ] || ( bool=false ; echo -e "Le fichier $2 est invalide" )
[ $bool ] || exit

regex='^([[:alnum:]]*):(.*)$'
trouve=false
i=1
n=0

DIC=`cat $2`
DIC=( $DIC )
PTXT=`cat $1`
PTXT=( $PTXT )
let "nbOcc=${#PTXT[@]} *  ${#PTXT[@]}"
let "maxComb=${#DIC[@]} * ${#DIC[@]} * ${#DIC[@]} + ${#DIC[@]} * ${#DIC[@]} + ${#DIC[@]} "
prompt=""
for LINE in `cat $1`
do
   if [[ "$LINE" =~ $regex ]]
   then
	Usr="${BASH_REMATCH[1]}"
	prompt="$prompt\nResearching password for $Usr ($i on ${#PTXT[@]} users)"
	Pass="${BASH_REMATCH[2]}"
	#echo $Pass
	#showBar $i $nbOcc
	for word1 in `cat $2`
	do
		if $trouve
		then 
			break
		fi

		newpass=$(perl -e'print crypt($ARGV[0], $ARGV[1])' $word1 $Pass)
		(( n++ ))
		if [[ "$Pass" =~ "$newpass" ]] 
		then
			prompt="$prompt\nPassword Find for $Usr : $word1"
			echo "$Usr : $word1" >>pass.txt
			trouve=true
			break
		fi
		for word2 in `cat $2`
		do	
			if $trouve
			then 
				break
			fi	
			(( n++ ))
			test=$word1$word2
			newpass=$(perl -e'print crypt($ARGV[0], $ARGV[1])' $test $Pass)
			if [[ "$Pass" =~ "$newpass" ]] 
			then
				prompt="$prompt\nPassword Find for $Usr : $test"
				echo "$Usr : $test" >>pass.txt
				trouve=true
				break
			fi

			for word3 in `cat $2`
	      		do
				(( n++ ))
				test=$word1$word2$word3
				newpass=$(perl -e'print crypt($ARGV[0], $ARGV[1])' $test $Pass)
				if [[ "$Pass" =~ "$newpass" ]] 
				then
					prompt="$prompt\nPassword Find for $Usr : $test"
					echo "$Usr : $test" >>pass.txt
					trouve=true
					break
				fi

			done
			showBar $n $maxComb $prompt
		done
	done
   else
       echo "Fail $LINE doesn't match"
   fi
   (( i++ ))
   #echo "Research for $Usr made : Password find = $trouve"
   prompt="$prompt\n$n Combinations studied"
   trouve=false
   n=0
done
echo "The results are stored in pass.txt"
let "t= $SECONDS / $i"
echo "The average time per user's password computation is $t s"
